/*
 * kylin-os-manager
 *
 * Copyright (C) 2022, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <QDebug>
#include <QDir>
#include <unistd.h>

#include "watcher.h"

namespace
{
constexpr char coreFilePath[] = "/var/lib/systemd/coredump";
}

namespace crash_collection
{

Watcher::Watcher()
{
    setWatcherPath(coreFilePath);
}

Watcher::~Watcher() {}

void Watcher::setWatch(bool flag)
{
    if (flag) {
        m_fileList = getFileList();
        connect(&m_fileSystemWatcher, &QFileSystemWatcher::directoryChanged, this, &Watcher::watcherCallback);
    } else {
        m_fileList.clear();
        disconnect(&m_fileSystemWatcher, &QFileSystemWatcher::directoryChanged, this, &Watcher::watcherCallback);
    }

    return;
}

bool Watcher::setWatcherPath(QString path)
{
    return m_fileSystemWatcher.addPath(path);
}

QList<QString> Watcher::getFileList(void)
{
    QDir dir(coreFilePath);
    return dir.entryList();
}

QList<QString> Watcher::getIncreaseFile(void)
{
    QDir dir(coreFilePath);
    QList<QString> currFileList = dir.entryList();

    for (int i = 0; i < m_fileList.size(); i++) {
        if (currFileList.contains(m_fileList.at(i))) {
            currFileList.removeAll(m_fileList.at(i));
        }
    }

    return currFileList;
}

void Watcher::watcherCallback(void)
{
    /* ToDo : Qt 监控到目录下文件变化 , 但此时 coredump 并没有将 core 信息记录到日志中 ,
     * 导致执行脚本时查询不到对应的崩溃信息 */
    sleep(3);

    QList<QString> increaseFileList = getIncreaseFile();

    /* 刷新文件列表 */
    m_fileList = getFileList();

    for (int i = 0; i < increaseFileList.size(); i++) {
        QList<QString> itemList = increaseFileList.at(i).split('.');
        if (itemList.size() == 7) {
            pid_t pid = itemList.at(4).toULongLong();
            if (pid != 0) {
                Q_EMIT crashPid(pid);
            }
        }
    }

    return;
}

} // namespace crash_collection